package mta.io;

import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Dmitry Nikolaev.
 * User: dima
 * Date: 21.01.2009
 * Time: 19:34:30
 */
public class LocalizationPackageFiles implements LocalizationPackageFilesIF {
    private String path;
    private List<String> packageFiles;

    public LocalizationPackageFiles(String path) {
        this.path = path;
    }

    public List<String> listFilenames() throws Exception {
        if (packageFiles == null) {
            File file = new File(path);
            if (!file.exists() || !file.isDirectory()) {
                throw new Exception("Folder " + path + " not exists");
            }
            packageFiles = new ArrayList<String>();
            peekFilesForDirectory("");
        }
        return packageFiles;
    }

    private void peekFilesForDirectory(String rPath) {
        File currDir = new File(getFullName(rPath));
        File[] files = currDir.listFiles();

        if (files != null) {
            for (File file : files) {
                String packageName = rPath + file.getName();
                if (file.isDirectory()) {
                    if (file.getName().charAt(0) != '.') { // .svn
                        peekFilesForDirectory(packageName + File.separator);
                    }
                } else {
                    if (FilenameUtils.getExtension(file.getName()).equals("csv")) {
                        packageFiles.add(packageName);
                    }
                }
            }
        }
    }

    public String getFullName(String file) {
        return path + file;
    }
}
